package meth

import (
	"github.com/go-ping/ping"
	"net"
	"time"
)

func PingIP(ip net.IP, timeout time.Duration) (bool, error) {
	p, _ := ping.NewPinger(ip.String()) // 修正：ip.String()
	p.SetPrivileged(true)
	p.Count = 1
	p.Timeout = timeout

	// 监听ARP更新事件
	arpUpdated := make(chan struct{})
	go func() {
		start := time.Now()
		for time.Since(start) < p.Timeout {
			_, err := ParseARP(ip.String())
			if err == nil { // ARP表存在记录
				close(arpUpdated)
				return
			}
			time.Sleep(50 * time.Millisecond)
		}
	}()

	// 启动Ping
	recvSignal := make(chan struct{})
	p.OnRecv = func(*ping.Packet) { close(recvSignal) }
	go p.Run()

	select {
	case <-recvSignal: // Case 1: ICMP响应
		return true, nil
	case <-arpUpdated: // Case 2: ARP表更新
		return true, nil
	case <-time.After(p.Timeout):
		return false, nil
	}
}

func generateIPs(a, b, c byte) []net.IP {
	var ips []net.IP
	for i := 1; i <= 254; i++ {
		ips = append(ips, net.IPv4(a, b, c, byte(i)))
	}
	return ips
}
